"""
@-*- coding: utf-8 -*-
@ python: 3.12.3
@ 创建者: JacksonCode
@ 创建时间: 2025-11-06
"""

"""
第一种
"""


def great():
    print("hello")


say_hello = great  # 把函数复制给变量
say_hello()

"""
第二种
"""


def call_func(func):
    func()


call_func(great)


# 手动写简单的装饰器
def my_decorator(func):
    def wrapper():
        print("调用前")
        func()
        print("调用后")

    return wrapper


# @my_decorator
def say():
    print("say")


# 手动应用装饰器
say_hi = my_decorator(say)
say_hi()


@my_decorator
def say_what():
    print("say_what")


say_what()


def up_wrapper(func):
    def wrapper(*args, **kwargs):
        print("开始执行")
        result = func(*args, **kwargs)
        print("执行结束")
        return result

    return wrapper


@up_wrapper
def add(a, b):
    return a + b


print(add(234, 62))


# 带参数的装饰器
def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                func(*args, **kwargs)

        return wrapper

    return decorator


@repeat(3)
def fn():
    print("PYTHON")


fn()

# 装饰后，原函数的 __name__、__doc__ 等元信息会丢失：

import functools


def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("执行中")
        return func(*args, **kwargs)

    return wrapper


@my_decorator
def hi():
    print("hi")


print(hi.__name__)  # hello ✅
print(hi.__doc__)  # 这是打招呼的函数 ✅

# 实际案例  计时器
import time


def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} 耗时:{time.time() - start:.4f}秒")
        return result

    return wrapper

@timer
def slow_func():
    time.sleep(1)

slow_func()